package com.mamba.microservice.mybatis.autoconfig;

import com.mamba.microservice.mybatis.config.MmsDataSourceProperties;
import com.mamba.microservice.mybatis.config.MybatisProperties;
import com.mamba.microservice.mybatis.utils.DbUtils;
import org.apache.commons.lang3.StringUtils;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.Assert;

import javax.sql.DataSource;


/**
 * Copyright ©2020 mamba All Rights Reserved
 * 请添加类/接口的说明：
 *
 * @Package: com.mamba.microservice.mysql.autoconfigure
 * @author: fangjin
 * @date: 2020年05月05日 19时22分
 */
@Configuration
@EnableConfigurationProperties({MmsDataSourceProperties.class, MybatisProperties.class})
public class MybatisDruidAutoConfiguration implements InitializingBean {

    public static final String MMS_SQL_SESSION_FACTORY_BEAN_NAME = "mmsSqlSessionFactoryBean";

    private MmsDataSourceProperties mmsDataSourceProperties;
    private MybatisProperties mybatisProperties;

    public MybatisDruidAutoConfiguration(MmsDataSourceProperties mmsDataSourceProperties, MybatisProperties mybatisProperties) {
        this.mybatisProperties = mybatisProperties;
        this.mmsDataSourceProperties = mmsDataSourceProperties;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        checkDataSourceProperties(mmsDataSourceProperties);
    }

    private void checkDataSourceProperties(MmsDataSourceProperties mmsDataSourceProperties) {
        boolean check = StringUtils.isNotEmpty(mmsDataSourceProperties.getUrl())
                && StringUtils.isNotEmpty(mmsDataSourceProperties.getUserName());
        Assert.isTrue(check, "please input the mms.datasource.url or the mms.datasource.username");
    }

    @Bean
    public DataSource dataSource() {
        return DbUtils.buildDruidDataSource(mmsDataSourceProperties);
    }

    @Bean(name = MMS_SQL_SESSION_FACTORY_BEAN_NAME)
    public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource) {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        sqlSessionFactoryBean.setConfigLocation(DbUtils.resolveMybatisConfigResource(mybatisProperties.getConfigLocation()));
        sqlSessionFactoryBean.setMapperLocations(DbUtils.resolveMapperLocations(mybatisProperties.getMapperLocations()));
        return sqlSessionFactoryBean;
    }
}
